package com.example.pda.ui.stock;

import android.annotation.SuppressLint;

import com.example.pda.common.BaseViewModel;
import com.example.pda.common.DaoUtils;
import com.example.pda.common.SharedUtils;
import com.example.pda.common.Utils;
import com.example.pda.data.Result;
import com.example.pda.data.model.GoodItem;
import com.example.pda.data.model.Inventory;
import com.example.pda.data.model.UploadBean;
import com.example.pda.net.ApiException;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class StockViewModel extends BaseViewModel {

//    public final MutableLiveData<List<GoodItem>> mDataBean = new MutableLiveData<>();
//

//
//    public void loadDjhItmByDjh(String djh) {
//        enqueue(api.getDjhItemByDjh(djh), true, new ResultCallback<List<GoodItem>>() {
//            @Override
//            public void onSuccess(List<GoodItem> goodItem) {
//                mDataBean.setValue(goodItem);
//            }
//
//            @Override
//            public void onError(int code, String msg) {
//                mDataBean.setValue(null);
//            }
//        });
//    }

    private final MutableLiveData<Result<GoodItem>> dataLive = new MutableLiveData<>();

    public MutableLiveData<Result<GoodItem>> getDataLive() {
        return dataLive;
    }

    @SuppressLint("CheckResult")
    public void queryListByLocal(String billType, List<GoodItem> items, GoodItem dataList) {
        Observable.just(1).map(new Function<Integer, GoodItem>() {
            @NonNull
            @Override
            public GoodItem apply(@NonNull Integer integer) throws Exception {
                return getDataListByType(billType, items, dataList);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<GoodItem>() {
                    @Override
                    public void accept(@NonNull GoodItem goodsData) throws Exception {
                        dataLive.postValue(new Result.Success<>(goodsData));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                        dataLive.postValue(new Result.Error<>(new Exception("查无此信息")));
                    }
                });
    }

    public GoodItem getDataListByType(String billType, List<GoodItem> items, GoodItem dataList) {
        if (Utils.isEmpty(items)) {
            Utils.LogI("getDataListByType  items is null.");
            return null;
        }
        Utils.LogI("getDataListByType  billType = " + billType);
        if (billType.equals("23")) {
            for (GoodItem item : items) {
                if (item.getGysname().equals(dataList.getGysname())
                        && item.getInvcode().equals(dataList.getInvcode())) {
                    dataList.setHgsl(item.getHgsl());
                    dataList.setGyscode(item.getGyscode());
                    dataList.setHwList(item.getHwList());
                    dataList.setStockList(item.getStockList());
                    dataList.setPch(item.getPch());
                    dataList.setYcsl(item.getYcsl());
                    dataList.setBhwcode(item.getBhwcode());
                    dataList.setBhwname(item.getBhwname());
                    dataList.setBstockcode(item.getBstockcode());
                    dataList.setBstockname(item.getBstockname());
                    GoodItem dbItem = DaoUtils.getsUtils().queryDataItem(dataList);
                    if (dbItem != null) {
                        dataList.setId(dbItem.getId());
                        dataList.setBhwcode(item.getBhwcode());
                        dataList.setBhwname(item.getBhwname());
                        dataList.setBstockcode(item.getBstockcode());
                        dataList.setBstockname(item.getBstockname());
                        dataList.setBz(dbItem.getBz());
                        dataList.setOriSl(dbItem.getSl());
                        dataList.setType(dbItem.getType());
                    }
                    return dataList;
                }
            }
        } else if (billType.equals("4455") || billType.equals("5X")) {
            for (GoodItem item : items) {
                if (item.getGysname().equals(dataList.getGysname())
                        && item.getGyspch().equals(dataList.getGyspch())
                        && item.getInvcode().equals(dataList.getInvcode())) {
                    Utils.LogI("getDataListByType current item = " + item.getInvcode());
                    dataList.setHgsl(item.getHgsl());
                    dataList.setGyscode(item.getGyscode());
                    dataList.setGyspch(item.getGyspch());
                    dataList.setHwList(item.getHwList());
                    dataList.setStockList(item.getStockList());
                    dataList.setPch(item.getPch());
                    dataList.setBhwcode(item.getBhwcode());
                    dataList.setBhwname(item.getBhwname());
                    dataList.setBstockcode(item.getBstockcode());
                    dataList.setBstockname(item.getBstockname());
                    dataList.setYcsl(item.getYcsl());
                    GoodItem dbItem = DaoUtils.getsUtils().queryDataItemPch(dataList);
                    if (dbItem != null) {
                        dataList.setId(dbItem.getId());
                        dataList.setBhwcode(item.getBhwcode());
                        dataList.setBhwname(item.getBhwname());
                        dataList.setBstockcode(item.getBstockcode());
                        dataList.setBstockname(item.getBstockname());
                        dataList.setBz(dbItem.getBz());
                        dataList.setOriSl(dbItem.getSl());
                        dataList.setType(dbItem.getType());
                    }
                    return dataList;
                }
            }
        }
        return null;
    }

    public MutableLiveData<Result<Object>> uploadResult = new MutableLiveData<>();

    public void upload(Inventory inventory, List<GoodItem> uploadItems) {
        getDialogMsg().setValue("上传中...");
        UploadBean uploadBean = new UploadBean();
        uploadBean.setDjh(inventory.getDjh());
        uploadBean.setBillType(inventory.getBillType());
        uploadBean.setUsercode(SharedUtils.getUserName());
        List<UploadBean.UploadItem> uploadBeans = new ArrayList<>();
        for (int i = 0; i < uploadItems.size(); i++) {
            GoodItem item = uploadItems.get(i);
            UploadBean.UploadItem bean = new UploadBean.UploadItem();
            bean.setInvcode(item.getInvcode());
            bean.setSl(item.getSl());
            bean.setPch(item.getPch());
            bean.setGyspch(item.getGyspch());
            bean.setHwcode(item.getBhwcode());
            bean.setStockcode(item.getBstockcode());
            bean.setGyscode(item.getGyscode());
            bean.setRemark(item.getBz());
            uploadBeans.add(bean);
        }
        uploadBean.setDataList(uploadBeans);
        /*Result<List<UploadBean>> result = new Result<>();
        result.setCode("0");
        result.setMsg("");
        result.setData(uploadBeans);*/
        String toJson = new Gson().toJson(uploadBean, UploadBean.class);
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), toJson);

        enqueue(api.upload(body), true, new ResultCallback<String>() {
            @Override
            public void onSuccess(String goodItem) {
                getShowDialog().setValue(false);
                DaoUtils.getsUtils().deleteAllCache(uploadItems);
                uploadResult.setValue(new Result.Success<>(new Object()));
            }

            @Override
            public void onError(int code, String msg) {
                getShowDialog().setValue(false);
                uploadResult.setValue(new Result.Error<>(new Exception(msg)));
            }
        });

    }

    /**
     * URLDecoder解码
     */
    public String toURLDecoder(String paramString) {
        if (paramString == null || paramString.equals("")) {
            return "";
        }
        try {
            String url = new String(paramString.getBytes(), "UTF-8");
            url = URLDecoder.decode(url, "UTF-8");
            return url;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

}